package com.example.springbootvue.controller;

import com.example.springbootvue.entity.User;
import com.example.springbootvue.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final PasswordEncoder passwordEncoder;

    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUsername = authentication.getName();

        log.info("获取用户信息: {}", currentUsername);

        User user = userService.findByUsername(currentUsername);
        if (user == null) {
            log.warn("未找到用户: {}", currentUsername);
            return new ResponseEntity<>(Map.of("message", "用户不存在"), HttpStatus.NOT_FOUND);
        }

        // 不返回密码
        user.setPassword(null);

        return ResponseEntity.ok(user);
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/me")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> updateUser(@RequestBody User userRequest) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUsername = authentication.getName();

        log.info("更新用户信息: {}", currentUsername);

        User user = userService.findByUsername(currentUsername);
        if (user == null) {
            log.warn("未找到用户: {}", currentUsername);
            return new ResponseEntity<>(Map.of("message", "用户不存在"), HttpStatus.NOT_FOUND);
        }

        // 允许更新邮箱和电话
        if (userRequest.getEmail() != null && !userRequest.getEmail().isEmpty()) {
            // 检查新邮箱是否被其他用户使用
            if (!user.getEmail().equals(userRequest.getEmail()) &&
                    userService.existsByEmail(userRequest.getEmail())) {
                return new ResponseEntity<>(Map.of("message", "邮箱已被使用"), HttpStatus.BAD_REQUEST);
            }
            user.setEmail(userRequest.getEmail());
        }

        if (userRequest.getPhone() != null) {
            user.setPhone(userRequest.getPhone());
        }

        userService.updateById(user);
        log.info("用户信息更新成功: {}", currentUsername);

        // 不返回密码
        user.setPassword(null);
        return ResponseEntity.ok(user);
    }

    /**
     * 更改密码
     */
    @PostMapping("/changePassword")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<?> changePassword(@RequestBody ChangePasswordRequest request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUsername = authentication.getName();

        log.info("修改用户密码: {}", currentUsername);

        // 验证请求
        if (request.getOldPassword() == null || request.getNewPassword() == null ||
                request.getOldPassword().isEmpty() || request.getNewPassword().isEmpty()) {
            return new ResponseEntity<>(Map.of("message", "旧密码和新密码不能为空"),
                    HttpStatus.BAD_REQUEST);
        }

        User user = userService.findByUsername(currentUsername);
        if (user == null) {
            log.warn("未找到用户: {}", currentUsername);
            return new ResponseEntity<>(Map.of("message", "用户不存在"), HttpStatus.NOT_FOUND);
        }

        // 验证旧密码
        if (!passwordEncoder.matches(request.getOldPassword(), user.getPassword())) {
            log.warn("旧密码验证失败: {}", currentUsername);
            return new ResponseEntity<>(Map.of("message", "旧密码不正确"), HttpStatus.BAD_REQUEST);
        }

        // 更新密码
        user.setPassword(passwordEncoder.encode(request.getNewPassword()));
        userService.updateById(user);

        log.info("密码修改成功: {}", currentUsername);
        return ResponseEntity.ok(Map.of("message", "密码修改成功"));
    }

    /**
     * 用户修改密码请求类
     */
    public static class ChangePasswordRequest {
        private String oldPassword;
        private String newPassword;

        public String getOldPassword() {
            return oldPassword;
        }

        public void setOldPassword(String oldPassword) {
            this.oldPassword = oldPassword;
        }

        public String getNewPassword() {
            return newPassword;
        }

        public void setNewPassword(String newPassword) {
            this.newPassword = newPassword;
        }
    }
}